using System;

namespace TDUnit.Common.TestData
{
    public class Column
    {
        private bool? shouldQuoteValue;
        private string colValue = string.Empty;

        #region Constructors

        public Column(string name)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentException("Name cannot be empty or null.");
            Name = name;
        }

        #endregion

        #region Public properties

        public string Name { get; private set; }

        public virtual string Value
        {
            get
            {
                return colValue;
            }
            set
            {
                colValue = value;
            }
        }

        public virtual bool ShouldQuote
        {
            get
            {
                return shouldQuoteValue.HasValue
                           ? shouldQuoteValue.Value
                           : (IsString() && Value.Equals("NULL") == false);
            }

            set
            {
                shouldQuoteValue = value;
            }
        }
        #endregion

        #region Public methods

        public Column WithValue(string value)
        {
            Value = value;
            return this;
        }

        public Column WithShouldQuote(bool? shouldQuote)
        {
            shouldQuoteValue = shouldQuote;
            return this;
        }

        #endregion

        #region Overrides

        public override bool Equals(object obj)
        {
            var c = obj as Column;
            return (
                       c != null &&
                       c.Name.Equals(Name) &&
                       c.Value.Equals(Value) &&
                       c.ShouldQuote == ShouldQuote);
        }

        public override int GetHashCode()
        {
            return (Name + Value + ShouldQuote).GetHashCode();
        }

        public override string ToString()
        {
            return Name;
        }

        #endregion

        #region Helper methods

        private static bool IsNumeric(string anyString)
        {
            if (anyString == null)
            {
                anyString = "";
            }
            if (anyString.Length <= 0)
            {
                return false;
            }

            double dummyOut;
            var cultureInfo = System.Globalization.CultureInfo.CurrentUICulture;

            return Double.TryParse(anyString, System.Globalization.NumberStyles.Any,
                                   cultureInfo.NumberFormat, out dummyOut);
        }

        private bool IsString()
        {
            return !IsNumeric(Value);
        }

        #endregion
    }
}